﻿using MediatR;
using Microsoft.IdentityModel.Tokens;
using SmartProduction.Domain;
using SmartProduction.ErrorCode;
using SmartProduction.Infarstructrue.Interface;
using SmartProduction.Read.API.Application.Commands.STaskCommand__生产管理;

namespace SmartProduction.Read.API.Application.CommandHandlers.STaskCommandHandler
{
    /// <summary>
    /// 处理
    /// </summary>
    public class STaskGetCommandHandler : IRequestHandler<STaskGetCommand, APIResult<APIPaing<STask>>>
    {
        private readonly IBaseRepository<STask> sTaskRepository;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="sTaskRepository"></param>
        public STaskGetCommandHandler(IBaseRepository<STask> sTaskRepository)
        {
            this.sTaskRepository = sTaskRepository;
        }
        public async Task<APIResult<APIPaing<STask>>> Handle(STaskGetCommand request, CancellationToken cancellationToken)
        {
            APIResult<APIPaing<STask>> result = new APIResult<APIPaing<STask>>();
            var entity = sTaskRepository.GetAll().Result.Where(x => x.IsDelete == 0);
            if (!string.IsNullOrEmpty(request.TaskName))
            {
                entity = entity.Where(x => x.TaskName.Contains(request.TaskName));
            }
            if (!string.IsNullOrEmpty(request.TaskNode))
            {
                entity = entity.Where(x => x.TaskNode.Contains(request.TaskNode));
            }
            if (request.TaskStatus != null)
            {
                entity = entity.Where(x => x.TaskStatus == request.TaskStatus);
            }
            if (request.MaterialServerId!=0)
            {
                entity = entity.Where(x => x.MaterialServerId == request.MaterialServerId);
            }
            int TotalCount = entity.Count();
            int PageCount = (int)Math.Ceiling(TotalCount * 1.0 / request.PageSize);
            entity = entity.OrderByDescending(x => x.Tid).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);

            APIPaing<STask> paing = new APIPaing<STask>();
            paing.TotalCount = TotalCount;
            paing.PageCount = PageCount;
            paing.Items = entity.ToList();
            result.Code = APIEnums.查询成功;
            result.Msg = APIEnums.查询成功.ToString();
            result.data = paing;
            return await Task.FromResult(result);
        }
    }
}
